package com.hileto.inf.utils.redis;

import java.util.ArrayList;
import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

public class Msgs {
	JedisPool jedisPool = null;

	public Msgs(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	public List<String> searchMessage(String key, Integer size) {
		Jedis jedis = jedisPool.getResource();
		long lstSize = jedis.llen(key);
		Transaction transaction = jedis.multi();
		int pageSize = size;
		if(lstSize < pageSize){
			pageSize = (int) lstSize;
		}
		List<String> msgList = new ArrayList<String>(pageSize);
		List<Response<String>> result = new ArrayList<Response<String>>();
		for (int i = 0; i < pageSize; i++) {
			result.add(transaction.lpop(key));
		}
		transaction.exec();
		for (Response<String> msg : result) {
			msgList.add(msg.get());
		}
		jedisPool.returnResource(jedis);
		return msgList;
	}
	
//	public List<String> searchMessage(String key, Integer size) {
//		List<String> msgList = null;
//		Jedis jedis = jedisPool.getResource();
//		Transaction transaction = jedis.multi();
//		if(size > 0){
//			msgList= transaction.lrange(key, 0, size).get();
//		}
//		int msgListSize = msgList.size();
//		if(msgListSize > 0){
//			long lstSize = transaction.llen(key).get();
//			transaction.ltrim(key, msgListSize, lstSize);
//		}
////		transaction.exec();
//		jedisPool.returnResource(jedis);
//		return msgList;
//	}

}
